<?php

namespace app\api\controller;

use app\api\model\AutoCategory;
use app\api\model\AutoService;
use app\api\model\ModelingServices as ModelingServiceModel;
use app\api\model\UserPayment as UserPaymentModel;
use app\api\model\Users;
use app\api\model\Wechat;
use app\common\controller\Api;
use think\Controller;
use think\Db;
use think\Request;
use Yansongda\Pay\Exceptions\GatewayException;

class UserPayment extends Api
{
    protected $noNeedLogin = ["modeling", "paymentResult", "payment"];
    protected $noNeedRight = ["*"];
    /**
     * 服务
     */
    public function modeling() {
        $categories = AutoCategory::getCategory();
        $categories? $this->success("请求成功", compact("categories")) : $this->error("暂无服务信息");
    }

    /**
     * 买单
     */
    public function payment(Wechat $wechat) {
        $type = $this->request->post('type');
        $money = $this->request->post('money');
        $service = $this->request->post('service/a');
        if ($service && is_array($service)) {
            $ids = array_column($service, 'service_id');
            $modelingServiceId = AutoService::getServiceId($ids);
            $money = ModelingServiceModel::getServiceMoney($modelingServiceId);
        }
        if ($money <= 0) {
            $this->error("支付金额必须大于0");
        }
        $user = Users::find($this->auth->getUserId());
//        $user = Users::find(11);
        if (!$user) {
            $this->error('用户不存在');
        }
        $data = [
            'order_no' => 'U'.date('YmdHis').$user->id,
            'payment' => $type,
            'user_id' => $user->id,
            'total_amount' => $money,
            'createtime' => time(),
            'updatetime' => time()
        ];
        //创建订单
        $order = UserPaymentModel::createOrder($data, $service);
        if ($order->total_amount <= 0) {
            $this->error("支付金额必须大于0");
        }
        switch ($type) {
            //余额支付
            case 1:
                if ($user->money <= 0 || $user->money < $order->total_amount) {
                    $this->error('账号余额不足，请先充值');
                }
                $this->paySuccess($order, $user);
                break;
            //微信支付
            case 2:
                try {
                    $res = $wechat->miniapp($order, $user->openid, config('wechat.notify_user_payment'));
                } catch (\Exception $e) {
                    throw new GatewayException($e->getMessage(), $e->getCode());
                }
                $res['order_no'] = $order->order_no;
                isset($e) ? $this->error('支付失败，请联系管理员') : $this->success('请求成功', $res);
                break;
            default:
                $this->error('支付类型无效');
                break;

        }

    }

    /**
     * 支付回调
     */
    public function notify(Wechat $wechat)
    {
        $order_no = $this->request->post('order_no');
        if (empty($order_no)) {
            $this->error('订单号不能为空');
        }
        $order = UserPaymentModel::where('order_no', $order_no)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->status == 1) {
            $this->success('支付成功', ['order_id' => $order->id]);
        }
        //查询支付结果
        $res = $wechat->find($order_no);
        if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
            if ($res['trade_state'] === 'SUCCESS') {
                $user = Users::find($order['user_id']);
                $this->paySuccess($order, $user);
            } else {
                $this->error($res['trade_state_desc'], [], $res['trade_state']);
            }
        } else {
            $this->error('支付失败，请联系管理员');
        }

    }

    /**
     * 支付结果通知
     */
    public function paymentResult(Wechat $wechat)
    {
        $res = $wechat->verify();
        if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
            $order = UserPaymentModel::where('order_no', $res['out_trade_no'])->find();
            if ($order && $order->status == 0) {
                $user = Users::find($order['user_id']);
                $this->paySuccess($order, $user);
            }
        }
        $wechat->wechatPay()->success()->send();
    }

    public function paySuccess($order, $user)
    {
        Db::startTrans();
        try {
            //订单
            $order->status = 1;
            $order->save();
            //扣除余额
            if ($order->payment == 1) {
                $user->money -= $order->total_amount;
            }
            //累积消费额
            $user->expense_money += $order->total_amount;
            $user->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        isset($e) ? $this->error($e->getMessage()) : $this->success('支付成功', ['order_id' => $order->id]);
    }
}
